package com.xia.demo.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 测试锁超时
 *
 * @author : xia
 * @date: 2023-05-03 13:58
 */
public class ReentrantLockTest3 {

    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            System.out.println("尝试获得锁");
            // 此时肯定获取失败, 因为主线程已经获得了锁对象
            try {
                // 等待1s
                if (!lock.tryLock(2, TimeUnit.SECONDS)) {
                    System.out.println("等待1s获取不到锁");
                    return;
                }
            } catch (InterruptedException e) {
                System.out.println("获取不到锁");
                return;
            }
            try {
                System.out.println("获得到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        System.out.println("获得到锁");
        t1.start();
        // 主线程2s之后才释放锁
        Thread.sleep(4000);
        System.out.println("释放了锁");
        lock.unlock();
    }

}


